let app = new Vue({
    el: "#search",
    data: {
        inputSearch: "",
        attrArr: [],
        tableData: [],
        loading: false,
        currentPath: "",
        qureyText: "",
        visible: false,
        tableHeight: 0,
        queryState: 0,
        currentTabData: [],
        loading: null,
        currentPage: 1,
        //当前页面条数
        pageSize: 20,
        showTable: [],
        showPage: 0,
        showSize: 15,
        showTotalPage: 0,
        count: 0,
        currentScrollTop: 0,
        showPath: "",
        pathKey: "",
        negation: false,
    },

    mounted() {
        let _this = this;
        window.onresize = () => {
            if (_this.resizeFlag) {
                clearTimeout(_this.resizeFlag);
            }
            _this.resizeFlag = setTimeout(() => {
                _this.getHeight();
                _this.resizeFlag = null;
            }, 100);
        };
    },
    created: function () {
        window.electronAPI.onMsessage((event, res) => {
            try {
                this.tableData = this.tableData.concat(
                    JSON.parse(JSON.stringify(res.rowsData))
                );
                this.attrArr = [];
                for (let i = 0; i < res.maxlen; i++) {
                    this.attrArr.push({ attrName: "attr_" + i });
                }
                this.currentTabData = this.tableData.slice(0, this.pageSize);
            } catch (error) {}
            this.getHeight();
            if (this.tableData.length == 0 && res.isOver) {
                this.notify("success", "没有数据哦");
                this.loading.close();
            } else {
                this.count++;
            }

            if (this.count == 1 || res.isOver) {
                //第一次有数据时，或者加载完成时
                this.updatePage();
                this.getHeight();
            }
            this.addevent();
            if (this.tableData.length > 0) {
                this.loading.close();
            }
            if (res.isOver) {
                this.notify(
                    "success",
                    `查询成功, 共${this.tableData.length}条数据.`
                );
            }
        });
    },
    methods: {
        notify(type, msg, duration = 1000) {
            let dom = document.querySelector(".el-notification__icon");
            if (!dom) {
                this.$notify({
                    type: type,
                    message: msg,
                    duration: duration,
                });
            }
        },
        addevent() {
            let _this = this;
            _this.preScrollDistance = 0;
            setTimeout(() => {
                let dom = document.querySelector(".el-table__body-wrapper");
                if (!dom) {
                    return;
                }
                dom.addEventListener("scroll", (v) => {
                    let scrollDistance =
                        dom.scrollHeight - dom.scrollTop - dom.clientHeight;
                    // 判断是否到底，可以加载下一页
                    if (
                        scrollDistance < 1 &&
                        _this.preScrollDistance != scrollDistance
                    ) {
                        // 判断是否全部加载完成
                        if (_this.showPage >= _this.showTotalPage) {
                            _this.notify("warning", "已经到底了...");
                        }
                        if (_this.showPage < _this.showTotalPage) {
                            //当前页数小于总页数就请求
                            // 加载下一页方法
                            _this.getNextList();
                        }
                    }
                    _this.preScrollDistance = scrollDistance;
                });
            }, 500);
        },

        getHeight() {
            this.tableHeight = window.innerHeight - 150;
            return this.tableHeight;
        },
        workbook2blob(workbook) {
            // 生成excel的配置项
            var wopts = {
                bookType: "xlsx", // 要生成的文件类型
                bookSST: false, // 是否生成Shared String Table
                type: "binary",
            };
            var wbout = XLSX.write(workbook, wopts);

            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf); //创建一个b的引用，类型是Uint8
                for (var i = 0; i !== s.length; ++i)
                    view[i] = s.charCodeAt(i) & 0xff;
                return buf;
            }
            let buf = s2ab(wbout);
            // 构造函数，接受两个参数，第一个为一个数据序列，可以是任意格式的值，例如，任意数量的字符串，Blobs 以及 ArrayBuffers。第二个参数，是一个包含了两个属性的对象
            var blob = new Blob([buf], {
                type: "application/octet-stream",
            });
            return blob;
        },

        exprotExcelAll(tableData) {
            if (this.currentTabData.length == 0) {
                this.notify("warning", "没有数据哦, 请先查询数据");
                return;
            }
            //此处是要导出到excel的数据，可以根据需要修改
            let sheetData = [];
            for (let dataIndex = 0; dataIndex < tableData.length; dataIndex++) {
                let obj = tableData[dataIndex];
                let list = [];
                list.push(obj["path"]);
                for (let key in obj) {
                    if (key == "path") {
                        continue;
                    }
                    list.push(obj[key]);
                }
                sheetData.push(list);
            }
            const sheet = XLSX.utils.aoa_to_sheet(sheetData);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, sheet, "过滤信息");
            const workbookBlob = this.workbook2blob(wb);
            saveAs(workbookBlob, "sheetjs.xlsx");
        },
        back() {
            window.gc();
            window.location.href = "../../index.html";
        },
        getWidth(attrName) {
            let newWidth = 0;
            for (let data in this.currentTabData) {
                let obj = this.currentTabData[data];
                let len = 0;
                if (obj[attrName]) {
                    len = obj[attrName].toString().length;
                }
                if (isNaN(Number(obj[attrName], 10))) {
                    newWidth = len * 14 + 30;
                } else {
                    newWidth = len * 12;
                }
                if (newWidth >= 200) {
                    newWidth = 200;
                }
                if (newWidth <= 80) {
                    newWidth = 80;
                }
                return newWidth;
            }
        },
        refresh() {
            this.tableData = [];
            this.currentTabData = [];
            this.showTable = [];
        },
        copyRow(row, column, event) {
            let text = row["path"];
            for (let key in row) {
                if (key == "path") {
                    continue;
                }
                text += "\t" + row[key];
            }
            this.copyText(text);
            this.notify("success", "复制一行成功");
        },
        copyCell(row, column, cell, event) {
            let text = cell.querySelector("div").innerText;
            // 模拟 输入框
            this.copyText(text);
            this.notify("success", `"${text}"复制成功`);
        },
        copyText(text) {
            var cInput = document.createElement("input");
            cInput.value = text;
            document.body.appendChild(cInput);
            cInput.select(); // 选取文本框内容
            document.execCommand("copy");
            document.body.removeChild(cInput);
        },
        send(data) {
            return window.electronAPI.sendMessage(data);
        },
        selectPath(type) {
            this.queryState = type;
            let prop = null;
            let filter = [];
            if (type == 2) {
                prop = ["openFile"];
                filter = [
                    { name: "Custom File Type", extensions: ["xlsx", "xls"] },
                ];
            } else if (type == 0 || type == 1) {
                prop = ["openDirectory"];
            }
            let data = {
                type: "excel",
                cmd: "selectPath",
                prop: prop,
                filter: filter,
            };
            this.send(data).then((res) => {
                if (res.length > 1) {
                    this.currentPath = res;
                } else {
                    this.currentPath = res[0];
                }
                if (this.currentPath.length > 20) {
                    this.showPath = this.currentPath.slice(
                        this.currentPath.length - 20
                    );
                }
            });
            this.visible = false;
        },
        query() {
            /**
             * 文件搜索
             */
            this.tableData = [];
            this.count = 0;

            if (!this.qureyText) {
                this.notify("warning", "请输入查询关键字!");
                return;
            }
            if (!this.currentPath) {
                this.notify("warning", "请选择文件/文件夹路径!");
                return;
            }

            let pathKeys = this.pathKey.split(",");
            if (!this.pathKey) {
                pathKeys = [];
            }
            let data = {
                type: "excel",
                cmd: "query",
                path: this.currentPath,
                text: this.qureyText,
                state: this.queryState,
                pathKeys: pathKeys,
                negation: this.negation,
            };
            this.loading = this.$loading({
                lock: true,
                text: "加载中未响应,请耐心等待......",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
            });
            this.send(data);
        },
        currentChange(index) {
            /**
             * 指定页码翻页
             * @index 页码
             */
            this.currentPage = index;
            let start = (index - 1) * this.pageSize;
            let end = start + this.pageSize;
            if (this.tableData.length < end) {
                end = this.tableData.length;
            }
            if (this.tableData.length < start) {
                start = this.tableData.length - this.pageSize;
            }
            this.currentTabData = this.tableData.slice(start, end);
            this.getHeight();
            this.updatePage();
            let dom = document.querySelector(".el-table__body-wrapper");
            dom.scrollTop = 0;
        },
        handleSizeChange(val) {
            /**
             * 每页展示大小改变时
             * @val 每页大小的值
             */
            this.pageSize = val;
            this.currentChange(this.currentPage);
        },
        updatePage() {
            /**
             * 更新滚动翻页的页数
             */
            this.showTotalPage = Math.ceil(this.pageSize / this.showSize);
            this.showPage = 0;
            this.showSize = 15;
            this.showTable = [];
            this.getNextList();
        },
        getNextList() {
            /**
             * 进行滚动翻页
             */
            let start = 0;
            let end = 14;
            if (this.tableData.length > 15) {
                this.showPage++; //当前页数自增
                start = (this.showPage - 1) * this.showSize;
                end = start + this.showSize;
            }

            if (end > this.pageSize) {
                end = this.pageSize;
            }

            this.showTable = this.showTable.concat(
                this.currentTabData.slice(start, end)
            );
            let dom = document.querySelector(".el-table__body-wrapper");
            this.addevent();
        },
    },
});
